package com.wolf.server;

import com.wolf.config.ServerProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @auth: dylan
 * @Desc: NettyServer端启动类
 * @Time: 2024/4/29
 */
@Slf4j
public class WolfNettyServer implements Runnable {
    private ServerProperties properties;

    public WolfNettyServer(ServerProperties properties) {
        this.properties = properties;
    }

    @Override
    public void run() {
        EventLoopGroup bossGroup = null;
        EventLoopGroup workGroup = null;
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bossGroup = new NioEventLoopGroup(1);
            workGroup = new NioEventLoopGroup(properties.getWorkThread());
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new WolfChannelInitializer());
            ChannelFuture future = bootstrap.bind(properties.getPort()).sync();
            log.info(" NettyServer started! The port on {}", properties.getPort());
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("NettyServer start fail~~~~");
            e.printStackTrace();
            System.exit(-1);
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }

    }
}
